import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
	ACCESS_TOKEN,
	INDEX_MAIN_PAGE_PATH
} from '@/store/mutation-types'
import {
	generateIndexRouter
} from "@/utils/util"
import eventBus from './components/eventBus.js'

NProgress.configure({
	showSpinner: false
}) // NProgress Configuration

const whiteList = ['/user/login', '/user/register', '/user/register-result',
	'/user/alteration', ] // no redirect whitelist

router.beforeEach((to, from, next) => {
	NProgress.start() // start progress bar
	if (Vue.ls.get(ACCESS_TOKEN)) {
		/* has token */
		console.log('---------------')
		console.log(to.path)//    /client/home
		if (to.path === '/user/login') {
			next({
				path: INDEX_MAIN_PAGE_PATH
			})
			NProgress.done()
		} 
		else if(to.path === '/client/home'){
			next()
		}
		else {
			// console.log(JSON.stringify(store.getters.permissionList))
			if (store.getters.permissionList.length === 0) {
				store.dispatch('GetPermissionList').then(res => {
						console.log(to.path)
						// const menuData = res.result.menu;
						let permissionData = []
						let homePageFlag = false
						for (let i = 0; i < res.data.menu.length; i++) {
							let menuList = res.data.menu[i]
							for (let j = 0; j < menuList.children.length; j++) {
								if (menuList.children[j].name == "dashboard/analysis") {
									homePageFlag = true
								}
							}
							permissionData.push.apply(permissionData, res.data.menu[i].children)
						}
						if (!homePageFlag) {
							console.log("插入首页")
							permissionData.push({
								"id": "",
								"parentId": "",
								"children": null,
								"key": null,
								"value": null,
								"name": "dashboard/analysis",
								"redirect": "",
								"path": "dashboard/analysis",
								"component": "dashboard/Analysis",
								"route": "true",
								"hiddenFlag": false,
								"meta": {
									"keepAlive": false,
									"internalOrExternal": false,
									"icon": "home",
									"title": "首页"
								}
							})
						}
						const menuData = permissionData;
						if (menuData === null || menuData === "" || menuData === undefined) {
							return;
						}
						let constRoutes = [];
						constRoutes = generateIndexRouter(menuData);

						// 添加主界面路由
						console.log(constRoutes)
						store.dispatch('UpdateAppRouter', {
							constRoutes
						}).then(() => {
							// 根据roles权限生成可访问的路由表
							// 动态添加可访问路由表
							console.log(store.getters.addRouters)
							router.addRoutes(store.getters.addRouters)
							const redirect = decodeURIComponent(from.query.redirect || to.path)
							console.log(redirect)
							setTimeout(() => {
								eventBus.$emit("changeNavgat", to.path)
							}, 300)
							if (to.path == '/community/communityProject' || to.path ==
								'/serviceProviders/storesProject' || to.path ==
								'/community/communitySteward' || to.path ==
								'/housemaking/stores/waiter' || to.path ==
								'/governmentManagement/procurement' || to.path ==
								'/assess/assessManagement/templateHandle' || to.path == 
								'/assess/assessManagement/questionnaire' || to.path == 
								'/assess/assessManagement/assessByElder' || to.path ==
								'/assess/assessManagement/internalQuestionnaire') {
								next({
									path: '/dashboard/analysis'
								})
								return
							}
							if (to.path === redirect) {
								// hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
								next({
									...to,
									replace: true
								})
							} else {
								// 跳转到目的路由
								next({
									path: redirect
								})

							}
						})
					})
					.catch((err) => {
						eventBus.$emit("permissionsErr", err)
						store.dispatch('Logout').then(() => {
							next({
								path: '/user/login',
								query: {
									redirect: to.fullPath
								}
							})
						})
					})
			} else {
				eventBus.$emit("changeNavgat", to.path)
				next()
			}
		}
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			// 在免登录白名单，直接进入
			next()
		} else {
			next({
				path: '/user/login',
				query: {
					redirect: to.fullPath
				}
			})
			NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
		}
	}
})

router.afterEach(() => {
	NProgress.done() // finish progress bar
})
